use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// HTTP 请求方法
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum HttpMethod {
    Get,
    Post,
    Put,
    Delete,
    Patch,
}

/// 请求参数
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RequestOptions {
    /// 请求方法
    pub method: HttpMethod,
    /// 请求URL
    pub url: String,
    /// URL查询参数
    #[serde(default)]
    pub params: HashMap<String, String>,
    /// 请求头
    #[serde(default)]
    pub headers: HashMap<String, String>,
    /// 请求体（JSON格式）
    #[serde(default)]
    pub body: Option<serde_json::Value>,
    /// 超时时间（秒）
    #[serde(default)]
    pub timeout: Option<u64>,
}

/// 响应结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResponseData {
    /// HTTP状态码
    pub status: u16,
    /// 响应头
    pub headers: HashMap<String, String>,
    /// 响应体（JSON格式）
    pub body: Option<serde_json::Value>,
    /// 响应体（文本格式）
    pub text: String,
}

/// 发起HTTP请求
#[tauri::command]
pub async fn http_request(options: RequestOptions) -> Result<ResponseData, String> {
    // 构建请求客户端
    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(options.timeout.unwrap_or(30)))
        .build()
        .map_err(|e| format!("创建HTTP客户端失败: {}", e))?;

    // 构建URL（添加查询参数）
    let mut url = reqwest::Url::parse(&options.url)
        .map_err(|e| format!("无效的URL: {}", e))?;
    
    for (key, value) in &options.params {
        url.query_pairs_mut().append_pair(key, value);
    }

    // 构建请求
    let mut request = match options.method {
        HttpMethod::Get => client.get(url),
        HttpMethod::Post => client.post(url),
        HttpMethod::Put => client.put(url),
        HttpMethod::Delete => client.delete(url),
        HttpMethod::Patch => client.patch(url),
    };

    // 添加请求头
    for (key, value) in &options.headers {
        request = request.header(key, value);
    }

    // 添加请求体
    if let Some(body) = options.body {
        request = request.json(&body);
    }

    // 发送请求
    let response = request
        .send()
        .await
        .map_err(|e| format!("请求失败: {}", e))?;

    // 获取状态码
    let status = response.status().as_u16();

    // 获取响应头
    let mut headers = HashMap::new();
    for (key, value) in response.headers() {
        if let Ok(value_str) = value.to_str() {
            headers.insert(key.to_string(), value_str.to_string());
        }
    }

    // 获取响应体
    let text = response
        .text()
        .await
        .map_err(|e| format!("读取响应失败: {}", e))?;

    // 尝试解析为JSON
    let body = serde_json::from_str(&text).ok();

    Ok(ResponseData {
        status,
        headers,
        body,
        text,
    })
}

/// 简化的GET请求
#[tauri::command]
pub async fn http_get(url: String, params: Option<HashMap<String, String>>) -> Result<ResponseData, String> {
    http_request(RequestOptions {
        method: HttpMethod::Get,
        url,
        params: params.unwrap_or_default(),
        headers: HashMap::new(),
        body: None,
        timeout: None,
    }).await
}

/// 简化的POST请求
#[tauri::command]
pub async fn http_post(
    url: String,
    body: Option<serde_json::Value>,
    headers: Option<HashMap<String, String>>,
) -> Result<ResponseData, String> {
    http_request(RequestOptions {
        method: HttpMethod::Post,
        url,
        params: HashMap::new(),
        headers: headers.unwrap_or_default(),
        body,
        timeout: None,
    }).await
}

